package cdu.notFound.controller;

import cdu.notFound.model.User;
import cdu.notFound.service.UserService;
import cdu.notFound.service.impl.UserServiceImpl;
import cdu.notFound.utils.LoginVerify;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * 用户头像更新
 * 限制10MB大小
 */
@MultipartConfig(maxFileSize = 1024 * 1024 * 10)
@WebServlet("/UpdateUserImgServlet")
public class UpdateUserImgServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		// 处理文件
		if(!LoginVerify.isLogin(request)){//判断是否登录
		    request.getRequestDispatcher("user/login.jsp?login-info="+java.net.URLEncoder.encode("你还没有登录！","UTF-8")).forward(request,response);
			return;
		}
		User user=(User)(request.getSession().getAttribute("loginUser"));
		UserService userService = new UserServiceImpl();
	    //更新信息
		user= userService.findById(user.getId());
		//获取上传的文件
		Part part = request.getPart("file");
		if(part==null){
			response.sendRedirect("user/personal.jsp?tab=info&info="+java.net.URLEncoder.encode("请选择文件","UTF-8"));
			return;
		}
		String savePath = request.getServletContext().getRealPath("static/user_img");
		String imagePathName = savePath + "/" + user.getId() + ".jpg";
		user.setImg(imagePathName);
		FileOutputStream fos = new FileOutputStream(imagePathName);
		byte[] bt = new byte[(int) part.getSize()];
		part.getInputStream().read(bt);
		fos.write(bt);
		userService.doUpdate(user);
		response.sendRedirect("user/personal.jsp?tab=info&info="+java.net.URLEncoder.encode("头像更新成功","UTF-8")+"&cache="+0);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		this.doGet(request, response);
	}
}
